package com.atung.service.impl;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.atung.dao.BusBoardingRecordDAO;
import com.atung.dao.BusCarAllocationDAO;
import com.atung.dao.BusCarRideDAO;
import com.atung.dao.BusOrderCarDAO;
import com.atung.dao.BusRoutPublishDAO;
import com.atung.dao.BusSchoolBusPaymentDAO;
import com.atung.model.BusBoardingRecord;
import com.atung.model.BusCarAllocation;
import com.atung.model.BusCarRide;
import com.atung.model.BusOrderCar;
import com.atung.model.BusRoutPublish;
import com.atung.model.BusSchoolBusPayment;
import com.atung.model.CompanionDTO;
import com.atung.tool.Dictionaries;
import com.atung.tool.SnowflakeIdWorker;
import com.google.common.base.Objects;
import com.yuyi.full.Result;

@Service
public class PaySuessOrderService {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Autowired
	private BusRoutPublishDAO busRoutPublishDAO;
	
	@Autowired
	private BusSchoolBusPaymentDAO busSchoolBusPaymentDao;
	
	@Autowired
	private BusCarAllocationDAO busCarAllocationDao;
	
	@Autowired
	private BusOrderCarDAO busOrderCarDAO;
	
	@Autowired
	private BusCarRideDAO busCarRideDAO;
	
	@Autowired
	private BusBoardingRecordDAO busBoardingRecordDAO;
	
	
	/**
	 * 修改支付流水
	 * @param busSchoolBusPayment
	 * @return
	 */
	public Boolean updateBusSchoolBusPayment(BusSchoolBusPayment busSchoolBusPayment){
		
		BusSchoolBusPayment busPayment=busSchoolBusPaymentDao.selectBusSchoolBusPaymentById(busSchoolBusPayment.getId());
		if(java.util.Objects.isNull(busPayment)||busPayment.getOrderStatus()!=201){
			return false;
		}
		return busSchoolBusPaymentDao.updateBusSchoolBusPayment(busSchoolBusPayment);
	}
	/**
	 * 用户支付成功
	 * @param OpenId
	 * @param paymentId
	 * @return 
	 * @throws Exception 
	 */
	@Transactional
	public Result  paySuessOrder(Long platformId) throws Exception{

		//报名成功
		BusSchoolBusPayment busSchoolBusPayment=busSchoolBusPaymentDao.selectBusSchoolBusPaymentById(platformId);
		if(!Objects.equal(busSchoolBusPayment.getOrderStatus(),202)){	
				throw new Exception("订单异常");	
		}
		Integer lockState=busRoutPublishDAO.lockStatePublishById(busSchoolBusPayment.getRoutPublishId());
		try{
			if(Objects.equal(lockState, 0)){
				busRoutPublishDAO.lockPublishById(busSchoolBusPayment.getRoutPublishId());
				String companions=stringRedisTemplate.opsForValue().get(Dictionaries.schoolBusOrderReidKey+busSchoolBusPayment.getPlatformOrderNumber());
				List<CompanionDTO>companionlist=JSON.parseArray(companions, CompanionDTO.class);
				//修改当前报名人数
				busRoutPublishDAO.updateCarCurrentNumberById(busSchoolBusPayment.getRoutPublishId(), companionlist.size());
				//获取当前发布信息
				BusRoutPublish busRoutPublish=busRoutPublishDAO.selectBusRoutPublishById(busSchoolBusPayment.getRoutPublishId());
			
				String allocationId="";
				//---------------------安排分配车辆
				Map<Object, Object>carAllocationMap=stringRedisTemplate.opsForHash().entries(Dictionaries.schoolRoutPublishRedisKey+busRoutPublish.getId());
				int maxAllocationNumber=busRoutPublish.getAllocationNumber();
				int companionSize=companionlist.size();
				Boolean hasNext=true;
				for(Object key:carAllocationMap.keySet()){
					String number=carAllocationMap.get(key).toString();
					Integer sumNumber=companionSize+Integer.parseInt(number);
					if(sumNumber<=maxAllocationNumber){
						BusCarAllocation busCarAllocation=busCarAllocationDao.selectBusCarAllocationById(Long.valueOf(key.toString()));
						if(busCarAllocation.getAllocationState()>=303){
							continue;
						} else{
							stringRedisTemplate.opsForHash().put(Dictionaries.schoolRoutPublishRedisKey+busRoutPublish.getId(),key.toString(), String.valueOf(sumNumber));
							allocationId=key.toString();
							hasNext=false;
							break;
						}
					}
				}
				BusCarAllocation busCarAllocation=new BusCarAllocation();
				
				busCarAllocation.setPublishId(busRoutPublish.getId());

				if(hasNext){
					allocationId= SnowflakeIdWorker.nextId().toString();
					stringRedisTemplate.opsForHash().put(Dictionaries.schoolRoutPublishRedisKey+busRoutPublish.getId(),allocationId, String.valueOf(companionSize));
					busCarAllocation.setCreationTime(LocalDateTime.now());
					busCarAllocation.setCurrentNember(companionSize);
					busCarAllocation.setId(Long.parseLong(allocationId));
					busCarAllocationDao.saveBusCarAllocation(busCarAllocation);	
				}else{
					Object currentNember=stringRedisTemplate.opsForHash().get(Dictionaries.schoolRoutPublishRedisKey+busRoutPublish.getId(), allocationId);
					busCarAllocation.setCurrentNember(Integer.parseInt(currentNember.toString()));
					busCarAllocation.setId(Long.valueOf(allocationId));
					busCarAllocation.setModificationTime(LocalDateTime.now());
					busCarAllocationDao.updateBusCarAllocation(busCarAllocation);
				}
				
				Long orderId=SnowflakeIdWorker.nextId();
				//新增订单信息
				BusOrderCar busOrderCar=new BusOrderCar();
				busOrderCar.setPaymentId(busSchoolBusPayment.getId());//支付流水编号
				busOrderCar.setAllocationId(Long.parseLong(allocationId));//车辆座位编号
				busOrderCar.setId(orderId);//订单id
				busOrderCar.setApplyNumber(companionlist.size());
				busOrderCar.setOpenId(busSchoolBusPayment.getOpenId());
				busOrderCar.setCreationTime(LocalDateTime.now());
				busOrderCar.setModificationTime(Instant.now());
				busOrderCar.setOrderState(300);
				busOrderCarDAO.saveBusOrderCar(busOrderCar);				
				for(CompanionDTO companion:companionlist){
					
					BusCarRide busCarRide=new BusCarRide();
					busCarRide.setOrderId(orderId);
					busCarRide.setAllocationId(Long.parseLong(allocationId));
					busCarRide.setRideName(companion.getCompanionName());
					busCarRide.setRidePhone(companion.getCompanionPhone());		
					busCarRide.setCreationTime(LocalDateTime.now());
					busCarRide.setModificationTime(LocalDateTime.now());
					busCarRideDAO.saveBusCarRide(busCarRide);
					
					BusBoardingRecord busBoardingRecord=new BusBoardingRecord();
					busBoardingRecord.setCity("城市");
					busBoardingRecord.setContact_name(companion.getCompanionName());
					busBoardingRecord.setContactPhone(companion.getCompanionPhone());
					busBoardingRecord.setDropOffPoint(busRoutPublish.getDestination());
					busBoardingRecord.setPickUpPoint(busRoutPublish.getDepartlName());
					busBoardingRecord.setDeparture_time(busRoutPublish.getStartData());
					
					busBoardingRecordDAO.saveBusBoardingRecord(busBoardingRecord);
				}
				//出发地+目的地+姓名 手机号 管理员 消息提醒
				
				
				return Result.success();

			}else{
	
			}
		}finally{
			busRoutPublishDAO.unlockPublishById(busSchoolBusPayment.getRoutPublishId());
		}
		
		return Result.error(102,"等一等");
		
		
		
	}


}
